package com.itheima.note.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.common.constants.ContentStatusConstants;
import com.itheima.common.constants.KafkaConstants;
import com.itheima.model.note.pojos.Note;
import com.itheima.note.service.NoteAuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 笔记审核服务实现
 */
@Service
@Slf4j
public class NoteAuditServiceImpl implements NoteAuditService {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Override
    @Async
    public void submitAudit(Note note) {
        try {
            // 构建审核任务
            Map<String, Object> auditTask = new HashMap<>();
            auditTask.put("taskId", UUID.randomUUID().toString());
            auditTask.put("contentType", ContentStatusConstants.ContentType.NOTE);
            auditTask.put("contentId", note.getId());
            auditTask.put("userId", note.getAuthor().getId());
            auditTask.put("textContent", note.getContent());
            auditTask.put("imageUrls", note.getImages());

            String taskJson = JSON.toJSONString(auditTask);

            // 发送到 Kafka
            kafkaTemplate.send(KafkaConstants.AuditTopics.NOTE_AUDIT_REQUEST, note.getId(), taskJson)
                    .addCallback(
                            success -> log.info("✅ 提交笔记审核成功: noteId={}", note.getId()),
                            failure -> log.error("❌ 提交笔记审核失败: noteId={}", note.getId(), failure)
                    );

            log.info("📤 异步提交笔记审核任务: noteId={}, taskId={}", note.getId(), auditTask.get("taskId"));

        } catch (Exception e) {
            log.error("❌ 提交笔记审核异常: noteId={}", note.getId(), e);
            // 不抛出异常，避免影响笔记发布流程
        }
    }
}

